let isLogin = false;

// 发布订阅模式
class Publisher {
  constructor() {
    this.map = new Map();
  }
  on(key, callback) {
    let arr = this.map.get(key) || [];
    arr.push(callback);
    this.map.set(key, arr);
  }
  emit(key, data = {}) {
    if (this.map.has(key)) {
      this.map.get(key).forEach((item) => {
        item.call(this, data);
      });
    }
  }
}

let publisher = new Publisher();

// 页面扩展
const oldPage = Page;
Page = function (params) {
  const { onLoad, onShow, onReady } = params;

  params.onLoad = function (p) {
    // 判断是否登陆
    if (isLogin) {
      onLoad?.call(this, p);
    } else {
      publisher.on("login", () => {
        isLogin = true;
        onLoad?.call(this, p);
      });
    }
  };

  params.onShow = function () {
    // 判断是否登陆
    if (isLogin) {
      onShow?.call(this);
    } else {
      publisher.on("login", () => {
        onShow?.call(this);
      });
    }
  };

  params.onReady = function () {
    // 判断是否登陆
    if (isLogin) {
      onReady?.call(this);
    } else {
      publisher.on("login", () => {
        onReady?.call(this);
      });
    }
  };
  return oldPage(params);
};

module.exports = {
  publisher,
};
